package com.qy.controller.manage;

import com.github.pagehelper.PageHelper;
import com.qy.base.core.*;
import com.qy.model.Toll;
import com.qy.service.TollService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.rmi.ServerException;
import java.util.Date;
import java.util.List;

import static com.qy.base.core.Constants.*;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController("Manage-TollController")
@RequestMapping("manage/toll")
public class TollController {
    @Resource
    private TollService tollService;

    //添加
    @PostMapping("/add")
    public Result add(@RequestBody Toll toll) {
        if (toll.getAmount() == null || toll.getAmount().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (toll.getType() == 2) {
            List<Toll> list = tollService.selectMemberPrice();
            if (list.size() >= 5) {
                throw new ServiceException(Constants.CODE_ERR_TOLL_NUMBER);
            }
        } else if (toll.getType() == 3) {
            List<Toll> list = tollService.selectRewardPrice();
            if (list.size() >= 3) {
                throw new ServiceException(Constants.CODE_ERR_TOLL_NUMBER);
            }
        }
        toll.setAdd_time(String.valueOf(new Date().getTime()));
        tollService.save(toll);
        return ResultGenerator.successResult();
    }

    //删除
    @PostMapping("/delete")
    public Result delete(@RequestBody Toll toll) {
        if (toll.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        tollService.deleteById(toll.getId());
        return ResultGenerator.successResult();
    }

    //编辑
    @PostMapping("/update")
    public Result update(@RequestBody Toll toll) {
        if (toll.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Toll toll1 = tollService.findById(toll.getId());
        if (toll1.getType() == 1) {
            toll1.setAmount(toll.getAmount());
        } else if (toll1.getType() == 2) {
            toll1.setAmount(toll.getAmount());
            toll1.setBars_number(toll.getBars_number());
        } else if (toll1.getType() == 3) {
            toll1.setAmount(toll.getAmount());
        } else {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        tollService.update(toll1);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Toll toll = tollService.findById(id);
        return ResultGenerator.successResult(toll);
    }

    //收费管理
    @GetMapping("/list")
    public Result list() {
        List<Toll> list = tollService.findAll();
        return ResultGenerator.successResult(list);
    }

}
